﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace SuperKit
{
    /// <summary>
    /// 此类是将一个目录下面的所有子目录（如果配置-self则只有自身）下面的图片文件统计，然后将[NumP]这样的数量追加到目录后面。
    /// </summary>
    class ImageCounter : CommandExecutor {
        public bool IsSelf { get; }
        // 如果为True，则表示[多少P]的会追加到前面
        public bool IsFront { get; }
        // 如果为True，则表示统计所有图片
        public bool IsAllFile { get; }
        // 如果为True，表示统计大小
        public bool IsSize { get; }
        // 如果为True，则不会增加标记，而是把已经有的标记删除
        public bool IsClear { get; }

        int count = 0;
        long size = 0;

        public ImageCounter(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            IsSelf = arg.IsContain("-self");
            IsFront = arg.IsContain("-front");
            IsAllFile = arg.IsContain("-all");
            IsSize = arg.IsContain("-size");
            IsClear = arg.IsContain("-clear");
        }

        public override void Execute() {
            Thread t = new Thread(StartProcess);
            t.Start();
        }

        private void StartProcess() {
            var dir = new DirectoryInfo(FilePath);

            if (IsSelf) {
                OnProcess(dir);
            } else {
                var dirs = dir.GetDirectories();
                if (dirs != null) {
                    foreach (var i in dirs) {
                        OnProcess(i);
                    }
                }
            }

            End();
        }

        private void OnProcess(DirectoryInfo info) {
            try {
                var files = new List<FileInfo>();
                if (IsAllFile) {
                    files = Kit.GetAllFiles(null, info);
                } else {
                    files = Kit.GetAllFiles(null, info, Kit.IMG_EXTS);
                }

                count = Kit.Len(files);
                size = 0;
                foreach (var file in files) {
                    size += file.Length;
                }
            } catch (IOException e) {
                Flush(e.Message);
                return;
            }

            var addition = string.Empty;
            if (IsSize) {
                addition = $"[{count}P][{GetSizeString(size)}]";
            } else {
                addition = $"[{count}P]";
            }

            var name = RemovePageText(info.Name.Trim());
            string newName;

            if (IsClear) {
                newName = name;
            } else {
                if (IsFront) {
                    newName = string.Format("{1}{0}", name, addition);
                } else {
                    newName = string.Format("{0}{1}", name, addition);
                }
            }
            

            var newPath = Path.Combine(info.Parent.FullName, newName);
            if (Directory.Exists(newPath)) {
                return;
            }
            try {
                Directory.Move(info.FullName, newPath);
                SetStatus("成功改名：{0}", newPath);
            } catch (IOException e) {
                Flush(e.Message);
            }
        }

        private static string GetSizeString(long size) {
            long mb = size / Kit.MB;
            if (mb > 1024) {
                return $"{mb / 1024}G";
            } else {
                return $"{mb}M";
            }
        }

        private static string RemovePageText(string s) {
            Regex r1 = new Regex(@"\[[0-9]+P\]");
            Regex r2 = new Regex(@"\[[0-9]+G\]");
            Regex r3 = new Regex(@"\[[0-9]+M\]");

            string newName = s;
            if (r1.IsMatch(newName)) {
                newName = r1.Replace(newName, "");
            }
            if (r2.IsMatch(newName)) {
                newName = r2.Replace(newName, "");
            }
            if (r3.IsMatch(newName)) {
                newName = r3.Replace(newName, "");
            }
            return newName;
        }

    }
}
